package com.hqyj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hqyj.dao.AdminMapper;
import com.hqyj.pojo.Admin;
import com.hqyj.service.AdminService;

import com.hqyj.utile.EmailUtil;
import com.hqyj.utile.MdFive;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.UUID;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;


/**
 * @Description
 * @Autor 伍军
 * @Date 2021/10/9 8:54
 * @Version 1.0
 **/
@Service
public class AdminServiceImpl implements AdminService {

    //注入mapper
    @Autowired(required = false)
    AdminMapper adminMapper;

    @Autowired
    EmailUtil emailUtil;

    //注入md5工具类
    @Autowired
    MdFive mdFive;

    @Override
    public HashMap<String, Object> select(Admin a) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        //定义分页对象
        Page<Admin> page = new Page<>(a.getPage(),a.getRow());

        //条件构造器
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq(a.getSysId()!=null,"sys_id",a.getSysId());
        queryWrapper.like(a.getSysName()!=null&&!a.getSysName().equals(""),"sys_name",a.getSysName());

            //查询数据库m
        Page<Admin> aList =adminMapper.selectPage(page,queryWrapper);
            //当前页集合
        map.put("list",aList.getRecords());
            //总页数
        map.put("totalPage",aList.getPages());
            //总条数
        map.put("total",aList.getTotal());
            //当前页
        map.put("curPage",a.getPage());
        if(a.getPage()==1){
                //上一页
                map.put("prePage",1);

        }else{
                map.put("prePage",a.getPage()-1);

        }
        if(a.getPage()==aList.getPages()){
                //下一页
                map.put("nextPage",aList.getPages());

        }else{
                map.put("nextPage",a.getPage()+1);

        }
            //每页显示条数
          map.put("row",a.getRow());

        return map;
    }

    @Override
    public HashMap<String, Object> add(Admin a) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        //创建条件构造器
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        //定义根据用户名查询的条件
        queryWrapper.eq("sys_name",a.getSysName());
        //查询用户名是否重名
        List<Admin> list = adminMapper.selectList(queryWrapper);
        if(list.size()>0){
            map.put("info","用户名重名");
        }else {
            //加密密码
            String p = mdFive.encrypt(a.getSysPwd(), a.getSalt());
            a.setSysPwd(p);
            //新增
            int num = adminMapper.insert(a);
            if(num>0){
                map.put("info","保存成功");
            }else{
                map.put("info","保存错误");
            }
        }

        return map;
    }

    @Override
    public HashMap<String, Object> update(Admin a) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        //创建条件构造器
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        //定义根据用户名查询的条件
        queryWrapper.eq("sys_name",a.getSysName());
        //查询用户名是否重名
        List<Admin> list = adminMapper.selectList(queryWrapper);
        if(list.size()>1){
            map.put("info","用户名重名");
        }else {
           /*
           也可以自动生成盐值 前端页面就不需要在显示修改盐值，可以盐值唯一加密
           String salt= UUID.randomUUID()+"";
            a.setSalt(salt);*/
            //加密密码
            String p = mdFive.encrypt(a.getSysPwd(), a.getSalt());
            a.setSysPwd(p);
            //修改
            int num = adminMapper.updateById(a);
            if(num>0){
                map.put("info","保存成功");
            }else{
                map.put("info","保存错误");
            }
        }

        return map;
    }

    @Override
    public HashMap<String, Object> del(Integer a) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        //删除
        int num = adminMapper.deleteById(a);
        if(num>0){
            map.put("info","保存成功");
        }else{
            map.put("info","保存错误");
        }
        return map;
    }

    @Override
    public HashMap<String, Object> login(Admin a, HttpServletRequest req) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        HttpSession session = req.getSession();
        //获取session中的验证码
        String code =(String)session.getAttribute(KAPTCHA_SESSION_KEY);
        //删除session中的验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        if(a.getCode()!=null&&a.getCode().equalsIgnoreCase(code)){
            try {
                //1.用户令牌（用户和密码对象）
                UsernamePasswordToken token = new UsernamePasswordToken(a.getSysName(), a.getSysPwd());
                //2 创建shiro的用户对对象
                Subject su = SecurityUtils.getSubject();
                //3 登录
                su.login(token);
                map.put("info","登录成功");
            } catch (UnknownAccountException e) {
                e.printStackTrace();
                map.put("info","用户名不正确");
                System.out.println("用户名不正确");
            }catch (IncorrectCredentialsException e){
                e.printStackTrace();
                map.put("info","密码不正确");
                System.out.println("密码不正确");
            }
        }else{
            map.put("info","验证码错误");
        }

        return map;
        /*QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(a.getSysName()!=null,"sys_name",a.getSysName());
        queryWrapper.eq(a.getSysPwd()!=null,"sys_pwd",a.getSysPwd());
        List<Admin> list = adminMapper.selectList(queryWrapper);
        if(a.getCode()!=null&&a.getCode().equalsIgnoreCase(code)){
            if(list.size()!=0){
                map.put("info","登录成功");
            }else {
                map.put("info","用户名或密码输入错误");
            }
        }else {
            map.put("info","验证码输入错误");
        }

        return map;*/
    }

    @Override
    public HashMap<String, String> getSendEmailCode(Admin a,HttpServletRequest request) {
        HashMap<String, String> map = new HashMap<>();
        String  checkCode= emailUtil.RandEmailCode();
        System.out.println(checkCode);
        //发送验证码
        if(a.getEmail().endsWith("@qq.com")){
            emailUtil.sendEmail(a.getEmail(),"账户注册验证码",checkCode);
            HttpSession session = request.getSession();
            session.setAttribute("emailCode",checkCode);
            //返回验证码
            map.put("info",checkCode);
        }else {
            map.put("info","邮件格式错误！请以@qq.com格式结尾。");
        }
        return map;
    }

    @Override
    public boolean updatePassWordByName(String sysName, String sysPwd, String salt) {
        //加密密码
        String p = mdFive.encrypt(sysPwd, salt);
        int n=adminMapper.updatePassWordByName(sysName,p);
        if(n==1){
            return true;
        }else {
            return false;
        }

    }


}
